package com.xinyue.cross.server.server;


import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 与网关连接的缓存，当需要推送时，从这里获取相关的网关连接信息
 */
public class CrossClientChannelCacheManager {
    private static Logger logger = LoggerFactory.getLogger(CrossClientChannelCacheManager.class);
    private static Map<String, ChannelHandlerContext> ctxCacheMap = new ConcurrentHashMap<>();

    public static void addCache(String gatewayNodeId, ChannelHandlerContext ctx) {
        ChannelHandlerContext preCtx = ctxCacheMap.get(gatewayNodeId);
        if (preCtx == null || preCtx != ctx) {
            ctxCacheMap.put(gatewayNodeId, ctx);
            ctx.channel().closeFuture().addListener(future -> {
                ctxCacheMap.remove(gatewayNodeId);
            });
        }
    }

    public static ChannelHandlerContext getNettyCtx(String gatewayNodeId) {
        return ctxCacheMap.get(gatewayNodeId);
    }
}
